﻿using System;
using System.Collections.Generic;
using System.Web;
using NVelocity;
using NVelocity.App;
using Commons.Collections;
using NVelocity.Runtime;
using System.IO;
using NVelocity.Context;
using System.Text;
using NewLife.Reflection;
using System.Diagnostics;

namespace BingZi.HY.Core
{
    /// <summary>
    /// NVelocity模板工具类 VelocityHelper
    /// </summary>
    public class VelocityHelper
    {
        private static VelocityEngine velocity = null;
        private IContext context = null;
        private BaseTemplatePage _Page = new BaseTemplatePage();
        /// <summary>
        /// 模版的页面
        /// </summary>
        public BaseTemplatePage Page
        {
            get { return _Page; }
            set { _Page = value; }
        }
   

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="pmb">集成模块的对象</param>
        public VelocityHelper(BaseTemplatePage __Page)
        {
            _Page = __Page;
            Init();
        }
 

        /// <summary>
        /// 初始话NVelocity模块
        /// </summary>
        public void Init()
        {
            if (velocity == null)
            {
                //创建VelocityEngine实例对象
                velocity = new VelocityEngine();
            }
 
         
            //使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();

            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,HttpContext.Current.Server.MapPath(Page.TemplatePath));
            //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.GetDirectoryName(HttpContext.Current.Request.PhysicalPath));
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");

            //模板的缓存设置
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, Page.Template_CacheEnable);              //是否缓存
            props.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)Page.Template_CacheTime);    //缓存时间(秒)

            props.AddProperty("directive.parse.max.depth", 2);     //解析深度

            velocity.Init(props);

            //为模板变量赋值
            context = new VelocityContext();
        }

        /// <summary>
        /// 给模板变量赋值
        /// </summary>
        /// <param name="key">模板变量</param>
        /// <param name="value">模板变量值</param>
        public void Put(string key, object value)
        {
            if (context == null)
                context = new VelocityContext();
            context.Put(key, value);
        }

        /// <summary>
        /// 显示模版
        /// </summary>
        /// <param name="templatFileName"></param>
        /// <returns></returns>
        public String Display(String templatFileName)
        {
            //检测是否存在此文件，若不存在将创建
            CreateTemplate(templatFileName);

  
            //从文件中读取模板
            Template template = velocity.GetTemplate(templatFileName);
            //添加共用变量
            context.Put("Module", _Page);

            String templateString = String.Empty;
            using (StringWriter writer = new StringWriter())
            {
                //合并模板
                template.Merge(context, writer);
                templateString = writer.GetStringBuilder().ToString();
                writer.Close();
            }

            return templateString;
        }

        public String Display(EnumTemplateFile TemplateFile)
        {
            return Display(EnumHelper.GetEnumTextVal((Int32)TemplateFile, typeof(EnumTemplateFile)));
        }

        /// <summary>
        /// 创建模版
        /// </summary>
        /// <param name="templatFileName"></param>
        public void CreateTemplate(String templatFileName)
        {
            String FullFileName = Page.Server.MapPath(String.Format("{0}{1}", Page.TemplatePath, templatFileName));
            FileInfo file = new FileInfo(FullFileName);
            if (!file.Exists)
            {
                if (!file.Directory.Exists)
                {
                    file.Directory.Create();
                }

                File.CreateText(FullFileName);
            }


        }



        /// <summary>
        /// 根据模板生成静态页面
        /// </summary>
        /// <param name="templatFileName"></param>
        /// <param name="htmlpath"></param>
        public void CreateHtml(string templatFileName, string htmlpath)
        {
            //从文件中读取模板
            Template template = velocity.GetTemplate(templatFileName);
            //合并模板
            StringWriter writer = new StringWriter(); 
            template.Merge(context, writer);
            using (StreamWriter write2 = new StreamWriter(HttpContext.Current.Server.MapPath(htmlpath), false, Encoding.UTF8, 200))
            {
                write2.Write(writer);
                write2.Flush();
                write2.Close();
            }

        }

        /// <summary>
        /// 根据模板生成静态页面
        /// </summary>
        /// <param name="templatFileName"></param>
        /// <param name="htmlpath"></param>
        public void CreateJS(string templatFileName, string htmlpath)
        {
            //从文件中读取模板
            Template template = velocity.GetTemplate(templatFileName);
            //合并模板
            StringWriter writer = new StringWriter();
            template.Merge(context, writer);
            using (StreamWriter write2 = new StreamWriter(HttpContext.Current.Server.MapPath(htmlpath), false, Encoding.UTF8, 200))
            {
                write2.Write(writer.ToString());
                write2.Flush();
                write2.Close();
            }

        }
    }

}




